<template>
  <div class="wrap-left-form">
    <el-form
      class="custom-form"
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      runningStatus-icon
      :inline="true"
    >
      <div class="form-group-title">基本信息</div>
      <div class="form-item-info">
        <!-- <el-form-item class="form-itme-width_20" label="项目名称" id="projectId" prop="projectId">
          <dc-select-dialog
            v-model="formData.projectId"
            type="input"
            objectName="executionProject"
            placeholder="请选择项目名称"
            :multiple="false"
            :disabled="isShow"
            @change="confirmProjectList"
          />
        </el-form-item> -->
        <el-form-item
          class="form-itme-width_20"
          label="配置模板"
          id="projectId"
          prop="projectId"
          @click="openProjectList"
        >
          <el-input
            :value="proxy.getKeyObject(PROJECT_MAP_CACHE, formData.projectId, 'projectName')"
            placeholder="请选择配置模板"
            clearable
          />
        </el-form-item>

        <el-form-item
          class="form-itme-width_20"
          label="单据类型"
          id="fBillTypeId"
          prop="fBillTypeId"
        >
          <el-select
            v-model="formData.fBillTypeId"
            clearable
            placeholder="请选择单据类型"
            @change="handleBillTypeChange"
          >
            <el-option-group v-for="group in groupedOptions" :key="group.id" :label="group.label">
              <el-option
                v-for="option in group.children"
                :key="option.id"
                :label="option.label"
                :value="option.dictKey"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item
          class="form-itme-width_20"
          label="销售组织"
          id="fSaleOrgDictId"
          prop="fSaleOrgDictId"
          v-if="formData.fParentBillTypeDictId == '1870708016893067265'"
        >
          <el-select v-model="formData.fSaleOrgDictId" clearable @change="handleSaleOrgChange">
            <el-option
              v-for="item in ORG_LIST_CACHE"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="form-itme-width_20"
          label="预测组织"
          id="fForeOrgDictId"
          prop="fForeOrgDictId"
          v-else
        >
          <el-select v-model="formData.fForeOrgDictId" clearable @change="handleFForeOrgChange">
            <el-option
              v-for="item in ORG_LIST_CACHE"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form-itme-width_20" label="销售员" id="fSalerId" prop="fSalerId">
          <el-select
            v-model="formData.fSalerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入人员名称进行搜索"
            :remote-method="remoteSalersOptions"
            clearable
            @change="handleFSalerChange"
          >
            <el-option
              v-for="item in SalersOptions"
              :key="item.fnumber"
              :label="item.fname"
              :value="item.fnumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="form-itme-width_20"
          label="销售部门"
          id="fSaleDeptName"
          prop="fSaleDeptName"
        >
          <el-input
            v-model="formData.fSaleDeptName"
            placeholder="选择销售员自动获取"
            clearable
            disabled
          />
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="日期" id="fDate" prop="fDate">
          <el-date-picker
            v-model="formData.fDate"
            type="date"
            clearable
            placeholder="请选择时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="客户" id="fCustId" prop="fCustId">
          <el-select
            v-model="formData.fCustId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入客户名称进行搜索"
            :remote-method="remoteCustomerOptions"
            @change="handleCustomerChange"
            clearable
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.customerFNumber"
              :label="item.customerFName"
              :value="item.customerFNumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="终端客户" id="fOraBase" prop="fOraBase">
          <el-select
            v-model="formData.fOraBase"
            filterable
            remote
            reserve-keyword
            placeholder="请输入终端客户进行搜索"
            :remote-method="remoteCustomerOptions"
            clearable
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.customerFNumber"
              :label="item.customerFName"
              :value="item.customerFNumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="TPM" id="fTpm" prop="fTpm">
          <el-select
            v-model="formData.fTpm"
            filterable
            remote
            reserve-keyword
            placeholder="请输入人员名称进行搜索"
            :remote-method="remoteTpmOptions"
            clearable
          >
            <el-option
              v-for="item in tpmOptions"
              :key="item.fnumber"
              :label="item.fname"
              :value="item.fnumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="运营跟单" id="fOraText3" prop="fOraText3">
          <el-select
            v-model="formData.fOraText3"
            filterable
            remote
            reserve-keyword
            placeholder="请输入运营跟单进行搜索"
            :remote-method="remoteDocumentariesOptions"
            clearable
          >
            <el-option
              v-for="item in documentariesOptions"
              :key="item.fnumber"
              :label="item.fname"
              :value="item.fnumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="项目类型" prop="fBdkText7">
          <el-select v-model="formData.fBdkText7" clearable placeholder="请选择项目类型">
            <el-option
              v-for="item in projectType"
              :key="item.id"
              :label="item.bizValue"
              :value="item.bizKey"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="订单类型" id="fOraCombo" prop="fOraCombo">
          <el-select v-model="formData.fOraCombo" clearable placeholder="请选择订单类型">
            <el-option
              v-for="item in DC_PMS_PROJECT_ORDER"
              :key="item.dictValue"
              :label="item.dictValue"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="form-itme-width_20" label="项目编号" id="fBdkBase" prop="fBdkBase">
          <el-select
            v-model="formData.fBdkBase"
            filterable
            remote
            reserve-keyword
            placeholder="请输入项目编号进行搜索"
            :remote-method="remoteProjectNumbersOptions"
            clearable
          >
            <el-option
              v-for="item in projectNumbersOptions"
              :key="item.id"
              :label="item.fname"
              :value="item.fnumber"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="formData.causeOfRejection"
          class="form-itme-width_100"
          label="驳回原因"
          id="causeOfRejection"
          prop="causeOfRejection"
        >
          <el-input text v-model="formData.causeOfRejection" clearable disabled />
        </el-form-item>
      </div>
    </el-form>
  </div>
  <div class="form-group-title form-group-header-title">销售订单明细</div>
  <div class="form-group-header-btn">
    <el-button type="primary" plain @click="handleAdd">新增</el-button>
    <el-button @click="handleDelete">删除</el-button>
    <el-button @click="handleCopy">复制行</el-button>
  </div>
  <el-form class="table-form" ref="ruleTableRef" :model="formData.dcErpOrderItemList[numberIndex]">
    <el-table
      ref="singleSelectTable"
      :data="formData.dcErpOrderItemList"
      @row-dblclick="handleRowDbclick"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      key="id"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="60" type="index">
        <template #default="scoped">
          <el-form-item v-if="editRowIndex === scoped.$index">
            <span>{{ (queryParams.current - 1) * queryParams.size + scoped.$index + 1 }}</span>
          </el-form-item>
          <span v-else>{{ (queryParams.current - 1) * queryParams.size + scoped.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="fMaterialId"
        label="物料编码"
        align="center"
        width="150"
        show-overflow-tooltip
      >
        <template #default="scoped">
          <el-form-item
            :id="`fMaterialId-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fMaterialId"
            :rules="{ required: true, message: '请选择物料编码', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fMaterialId"
              filterable
              remote
              reserve-keyword
              :remote-method="remoteFMaterialOptions"
              @change="handleFMaterialChange(scoped.row)"
              clearable
              @click.stop
            >
              <el-option
                v-for="item in materialsOptinons"
                :key="item.id"
                :label="item.fnumber"
                :value="item.fnumber"
              />
            </el-select>
          </el-form-item>
          <span v-else>{{ scoped.row.fMaterialId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fMaterialName"
        label="物料名称"
        align="center"
        width="130"
        show-overflow-tooltip
      >
        <template #default="scoped">
          <el-form-item
            :id="`fMaterialName-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fMaterialName"
            :rules="{ required: true, message: '请选择物料名称', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fMaterialName"
              filterable
              remote
              reserve-keyword
              :remote-method="remoteMaterialsOptions"
              @change="handleMaterialChange(scoped.row)"
              clearable
              @click.stop
            >
              <el-option
                v-for="item in materialsOptinons"
                :key="item.id"
                :label="item.fname"
                :value="item.fname"
              />
            </el-select>
          </el-form-item>
          <span v-else>{{ scoped.row.fMaterialName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="contactsDeptName"
        label="存货类别"
        align="center"
        show-overflow-tooltip
      >
        <template #default="scoped">
          <el-form-item
            :id="`contactsDeptName-${scoped.$index}`"
            prop="contactsDeptName"
            v-if="editRowIndex === scoped.$index"
          >
            {{ scoped.row.contactsDeptName || '-' }}
          </el-form-item>
          <span v-else>{{ scoped.row.contactsDeptName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fMaterialModel"
        label="规格型号"
        align="center"
        width="150"
        show-overflow-tooltip
      >
        <template #default="scoped">
          <el-form-item
            :id="`fMaterialModel-${scoped.$index}`"
            prop="fMaterialModel"
            v-if="editRowIndex === scoped.$index"
          >
            {{ scoped.row.fMaterialModel || '-' }}
          </el-form-item>
          <span v-else>{{ scoped.row.fMaterialModel || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fIsPrecisionPart" label="精密件" align="center" show-overflow-tooltip>
        <template #default="scoped">
          <el-form-item
            :id="`fMaterialModel-${scoped.$index}`"
            prop="fMaterialModel"
            v-if="editRowIndex === scoped.$index"
          >
            {{ scoped.row.fMaterialModel || '-' }}
          </el-form-item>
          <span v-else>{{ scoped.row.fMaterialModel || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="ff100001" label="喷砂亮银" align="center" show-overflow-tooltip>
        <template #default="scoped">
          <el-form-item
            :id="`ff100001-${scoped.$index}`"
            prop="ff100001"
            v-if="editRowIndex === scoped.$index"
          >
            {{ scoped.row.ff100001 || '-' }}
          </el-form-item>
          <span v-else>{{ scoped.row.ff100001 || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fVersionNo"
        label="版本号"
        align="center"
        v-if="formData.fParentBillTypeDictId == '1870708016893067265'"
      >
        <template #default="scoped">
          <el-form-item
            :id="`fVersionNo-${scoped.$index}`"
            prop="fVersionNo"
            v-if="editRowIndex === scoped.$index"
            :rules="getVersionRules()"
          >
            <el-select
              v-model="scoped.row.fVersionNo"
              clearable
              v-if="editRowIndex === scoped.$index"
              @click.stop
            >
              <el-option
                v-for="item in fVersionNoType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <span v-else>{{ scoped.row.fVersionNo || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fUnitId" label="单位" align="center" width="120">
        <template #default="scoped">
          <el-form-item
            :id="`fUnitId-${scoped.$index}`"
            prop="fUnitId"
            v-if="editRowIndex === scoped.$index"
          >
            <div>
              {{ scoped.row.fUnitId || '-' }}
            </div>
          </el-form-item>
          <span v-else>{{ scoped.row.fUnitId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fQty" label="销售数量 " align="center" width="140">
        <template #default="scoped">
          <el-form-item
            :id="`fQty-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fQty"
            :rules="{ required: true, message: '请输入销售数量', trigger: 'change' }"
          >
            <el-input-number
              v-if="editRowIndex === scoped.$index"
              v-model="scoped.row.fQty"
              controls-position="right"
              placeholder="销售数量"
              @click.stop
            />
          </el-form-item>
          <span v-else>{{ scoped.row.fQty || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fDeliveryDate" label="客户交期ETD " align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fDeliveryDate-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fDeliveryDate"
            :rules="{ required: true, message: '请选择客户交期ETD', trigger: 'change' }"
          >
            <el-date-picker
              style="display: inline-block"
              v-model="scoped.row.fDeliveryDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              @click.stop
            />
          </el-form-item>
          <span v-else> {{ scoped.row.fDeliveryDate || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fBdkText8" label="内部PM" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fBdkText8-${scoped.$index}`"
            prop="fBdkText8"
            v-if="editRowIndex === scoped.$index"
          >
            <dc-select-user
              v-if="editRowIndex === scoped.$index"
              v-model="scoped.row.fBdkText8"
              placeholder="请选择内部PM"
              returnType="string"
              :multiple="false"
              :multiple-limit="1"
              @click.stop
            />
          </el-form-item>
          <span v-else>
            <dc-view v-model="scoped.row.fBdkText8" objectName="user" showKey="realName"
          /></span>
        </template>
      </el-table-column>
      <el-table-column prop="fBdkText9" label="机构工程" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fBdkText9-${scoped.$index}`"
            prop="fBdkText9"
            v-if="editRowIndex === scoped.$index"
          >
            <dc-select-user
              v-if="editRowIndex === scoped.$index"
              v-model="scoped.row.fBdkText9"
              placeholder="请选择机构工程"
              returnType="string"
              :multiple="false"
              :multiple-limit="1"
              @click.stop
            />
          </el-form-item>
          <span v-else>
            <dc-view v-model="scoped.row.fBdkText9" objectName="user" showKey="realName"
          /></span>
        </template>
      </el-table-column>
      <el-table-column prop="fBdkText10" label="电气工程" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fBdkText10-${scoped.$index}`"
            prop="fBdkText10"
            v-if="editRowIndex === scoped.$index"
          >
            <dc-select-user
              v-if="editRowIndex === scoped.$index"
              v-model="scoped.row.fBdkText10"
              placeholder="请选择电气工程"
              returnType="string"
              :multiple="false"
              :multiple-limit="1"
              @click.stop
            />
          </el-form-item>
          <span v-else>
            <dc-view v-model="scoped.row.fBdkText10" objectName="user" showKey="realName"
          /></span>
        </template>
      </el-table-column>
      <el-table-column prop="fBdkText11" label="电子工程师" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fBdkText11-${scoped.$index}`"
            prop="fBdkText11"
            v-if="editRowIndex === scoped.$index"
          >
            <dc-select-user
              v-model="scoped.row.fBdkText11"
              placeholder="请选择电气工程"
              returnType="string"
              :multiple="false"
              :multiple-limit="1"
              @click.stop
            />
          </el-form-item>
          <span v-else>
            <dc-view v-model="scoped.row.fBdkText11" objectName="user" showKey="realName"
          /></span>
        </template>
      </el-table-column>
      <el-table-column prop="fBdkText12" label="软件工程" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fBdkText12-${scoped.$index}`"
            prop="fBdkText12"
            v-if="editRowIndex === scoped.$index"
          >
            <dc-select-user
              v-model="scoped.row.fBdkText12"
              placeholder="请选择电气工程"
              returnType="string"
              :multiple="false"
              :multiple-limit="1"
              @click.stop
            />
          </el-form-item>
          <span v-else>
            <dc-view v-model="scoped.row.fBdkText12" objectName="user" showKey="realName"
          /></span>
        </template>
      </el-table-column>

      <el-table-column prop="fEwPhase" label="阶段" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwPhase-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fEwPhase"
            :rules="{ required: true, message: '请选择阶段', trigger: 'change' }"
          >
            <el-select
              v-if="editRowIndex === scoped.$index"
              v-model="scoped.row.fEwPhase"
              clearable
              placeholder="请选择阶段"
              @click.stop
            >
              <el-option
                v-for="item in stageType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>{{ scoped.row.fEwPhaseName || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="fEwCostType" label="成本类型" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwCostType-${scoped.$index}`"
            prop="fEwCostType"
            v-if="editRowIndex === scoped.$index"
          >
            <el-select
              v-model="scoped.row.fEwCostType"
              clearable
              placeholder="请选择成本类型"
              @click.stop
            >
              <el-option
                v-for="item in costType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>
            {{ scoped.row.fEwCostTypeName || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="fEwFreeReason" label="免费原因" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwFreeReason-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fEwFreeReason"
            :rules="{ required: true, message: '请输入免费原因', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fEwFreeReason"
              clearable
              placeholder="请选择免费原因"
              @click.stop
            >
              <el-option
                v-for="item in fEwFreeReasonType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>
            {{ scoped.row.fEwFreeReasonName || '-' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="fEwCustomerProduct" label="客户产品" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwCustomerProduct-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fEwCustomerProduct"
            :rules="{ required: true, message: '请选择客户产品', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fEwCustomerProduct"
              clearable
              placeholder="请选择成本类型"
              @click.stop
            >
              <el-option
                v-for="item in productSeriationType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>
            {{ scoped.row.fEwCustomerProduct || '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="fEwProjectType" label="项目类型" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwProjectType-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fEwProjectType"
            :rules="{ required: true, message: '请选择项目类型', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fEwProjectType"
              clearable
              placeholder="请选择项目类型"
              @click.stop
            >
              <el-option
                v-for="item in projectType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>
            {{ scoped.row.fEwProjectTypeName || '-' }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="fEwDeviceAttribute" label="设备属性" align="center" width="180">
        <template #default="scoped">
          <el-form-item
            :id="`fEwDeviceAttribute-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fEwDeviceAttribute"
            :rules="{ required: true, message: '请选择设备属性', trigger: 'change' }"
          >
            <el-select
              v-model="scoped.row.fEwDeviceAttribute"
              clearable
              placeholder="请选择设备属性"
              @click.stop
            >
              <el-option
                v-for="item in fEwDeviceAttributeType"
                :key="item.id"
                :label="item.bizValue"
                :value="item.bizKey"
              />
            </el-select>
          </el-form-item>
          <span v-else>
            {{ scoped.row.fEwDeviceAttributeName || '-' }}
          </span>
        </template>
      </el-table-column>

      <!-- <el-table-column prop="fOraText5" label="客户交期ETA" align="center" width="180">
        <template #default="scoped">
          <el-date-picker
            v-if="editRowIndex === scoped.$index"
            v-model="scoped.row.fOraText5"
            type="date"
            placeholder="请选择日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
          <span v-else>{{ scoped.row.fOraText5 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="fExchangeRate"
        label="汇率"
        align="center"
        width="150"
        v-if="formData.fParentBillTypeDictId == '1870708551385808898'"
      >
        <template #default="scoped">
          <el-form-item
            :id="`fExchangeRate-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fExchangeRate"
            :rules="{ required: true, message: '请输入汇率', trigger: 'change' }"
          >
            <el-input-number
              v-model="scoped.row.fExchangeRate"
              controls-position="right"
              @click.stop
            />
          </el-form-item>
          <span v-else>{{ scoped.row.fExchangeRate || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fOraTaxRate"
        label="税率"
        align="center"
        width="150"
        v-if="formData.fParentBillTypeDictId == '1870708551385808898'"
      >
        <template #default="scoped">
          <el-form-item
            :id="`fOraTaxRate-${scoped.$index}`"
            v-if="editRowIndex === scoped.$index"
            prop="fOraTaxRate"
            :rules="{ required: true, message: '请输入税率', trigger: 'change' }"
          >
            <el-input-number
              v-model="scoped.row.fOraTaxRate"
              controls-position="right"
              @click.stop
            />
          </el-form-item>
          <span v-else>{{ scoped.row.fOraTaxRate || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        fixed="right"
        width="155"
        v-if="editRowIndex || editRowIndex > -1"
      >
        <template #default="scoped">
          <div v-if="editRowIndex === scoped.$index">
            <el-button text type="success" @click.stop="configSubmit(scoped.row, scoped.$index)"
              >确定</el-button
            >
            <el-button text type="success" @click.stop="Cancel(scoped.row, scoped.$index)"
              >取消</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-form class="custom-form" label-width="120px" :inline="true" v-if="info.createUser != null">
      <div class="form-item-info mt-5 form-display">
        <el-form-item label="发起人">
          <dc-view v-model="info.createUser" objectName="user"
        /></el-form-item>
        <el-form-item label="发起时间">
          {{ info.createTime }}
        </el-form-item>
        <el-form-item label="发起部门">
          <dc-view v-model="info.createDept" objectName="dept"
        /></el-form-item>
      </div>
    </el-form>
    <div class="mt-5">
      <el-button @click="submit" :disabled="!passDisabled">保存</el-button>
      <el-button type="primary" @click="passSubmit" :disabled="!passDisabled">提交</el-button>
    </div>
  </el-form>
  <!--项目列表-->
  <ExecutionList :isDialog="true" @confirm="confirmProjectList" ref="ProjectListRef" />

  <!-- 选择主管 -->
  <el-dialog
    v-model="dialogVisible"
    title="提交主管审核"
    :close-on-click-modal="false"
    width="30%"
    align-center
    class="audit"
  >
    <el-form>
      <el-form-item label="选择主管">
        <el-select v-model="formData.selectedSupervisor" placeholder="请选择">
          <el-option
            v-for="item in roleIdOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmReject(formData.selectedSupervisor)">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup name="executionSubmit">
import Api from '@/api';
import { reactive, toRefs, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const pageData = reactive({
  loading: false,
  queryParams: {
    current: 1,
    size: 10,
  },
  formData: {
    fBillTypeId: 'XSDD02',
    fBillTypeDictId: '1870708114469355522',
    fParentBillTypeDictId: '1870708016893067265',
    fSaleOrgDictId: '100006',
    fSaleOrgId: 'JL',
    realFOrgId: '100006',
    // 预测组织
    fForeOrgDictId: '100006',
    fForeOrgId: 'JL',
    dcErpOrderItemList: [],
    fEwProjectTypeOptions: [],
  },
  ProjectListRef: null,

  // 字典
  projectType: [],
  fHeadDeliveryWayType: [],
  reservationType: [],
  costType: [],
  stageType: [],
  /*
   * 表格字段
   */
  // 单位
  unitType: [],
  // 表格免费原因
  fEwFreeReasonType: [],
  // erp查询
  customerOptions: [],
  currenciesOptinons: [],
  // 物料编码
  materialsOptinons: [],
  // tpm
  tpmOptions: [],
  // 收款条件
  CollectionTermsOptions: [],
  // 销售员
  SalersOptions: [],
  // 运营跟单
  documentariesOptions: [],
  // 版本号
  fVersionNoType: [
    { label: 'A', value: 'A' },
    { label: 'B', value: 'B' },
    { label: 'C', value: 'C' },
    { label: 'D', value: 'D' },
    { label: 'E', value: 'E' },
    { label: 'F', value: 'F' },
    { label: 'G', value: 'G' },
    { label: 'H', value: 'H' },
    { label: 'I', value: 'I' },
    { label: 'J', value: 'J' },
    { label: 'K', value: 'K' },
    { label: 'L', value: 'L' },
    { label: 'M', value: 'M' },
    { label: 'N', value: 'N' },
    { label: 'O', value: 'O' },
    { label: 'P', value: 'P' },
    { label: 'Q', value: 'Q' },
    { label: 'R', value: 'R' },
    { label: 'S', value: 'S' },
    { label: 'T', value: 'T' },
    { label: 'U', value: 'U' },
    { label: 'V', value: 'V' },
    { label: 'W', value: 'W' },
    { label: 'X', value: 'X' },
    { label: 'Y', value: 'Y' },
    { label: 'Z', value: 'Z' },
  ],
  openConfig: false,
  editRowIndex: null, // 当前正在编辑的行索引
  rules: {
    fBillTypeId: { required: true, message: '请选择单据类型', trigger: 'change' },
    fSaleOrgDictId: { required: true, message: '请选择销售组织', trigger: 'change' },
    fSalerId: { required: true, message: '请选择销售员', trigger: 'change' },
    fSaleDeptName: { required: true, message: '请选择销售部门', trigger: 'change' },
    fDate: { required: true, message: '请选择日期', trigger: 'change' },
    fCustId: { required: true, message: '请选择客户', trigger: 'change' },
    fOraBase: { required: true, message: '请选择终端客户', trigger: 'change' },
    fTpm: { required: true, message: '请选择TPM', trigger: 'change' },
    fOraText3: { required: true, message: '请选择运营跟单', trigger: 'change' },
    fForeOrgDictId: { required: true, message: '请选择预测组织', trigger: 'change' },
    fBdkText7: { required: true, message: '请选择项目', trigger: 'change' },
    fOraCombo: { required: true, message: '请选择订单类型', trigger: 'change' },
    fBdkBase: { required: true, message: '请选择项目编号', trigger: 'change' },
  },
  originalRowData: null,
  singleSelectTable: null,
  selectedRow: null,
  numberIndex: null,
  dialogVisible: false,
  roleIdOptions: [],
  // 项目编号
  projectNumbersOptions: [],
  // 客户产品
  productSeriationType: [],
  // 设备属性
  fEwDeviceAttributeType: [],
  passDisabled: true,
  fparentId: '',
});

const {
  numberIndex,
  rules,
  formData,
  queryParams,
  loading,
  ProjectListRef,
  projectType,
  fHeadDeliveryWayType,
  fEwFreeReasonType,
  unitType,
  costType,
  reservationType,
  stageType,
  customerOptions,
  currenciesOptinons,
  materialsOptinons,
  fVersionNoType,
  CollectionTermsOptions,
  SalersOptions,
  tpmOptions,
  documentariesOptions,
  openConfig,
  editRowIndex,
  originalRowData,
  singleSelectTable,
  selectedRow,
  dialogVisible,
  roleIdOptions,
  projectNumbersOptions,
  productSeriationType,
  fEwDeviceAttributeType,
  passDisabled,
  fparentId,
} = toRefs(pageData);

const props = defineProps({
  // 详情
  info: {
    type: Object,
    default: {},
  },
});

// 数据字典
const { DC_BILL_TYPE, ORG_LIST_CACHE, DC_PMS_PROJECT_ORDER, PROJECT_MAP_CACHE } = proxy.useCache([
  { key: 'DC_BILL_TYPE' },
  { key: 'ORG_LIST_CACHE' },
  { key: 'DC_PMS_PROJECT_ORDER' },
  { key: 'PROJECT_MAP_CACHE', keyName: 'id' },
]);

onMounted(() => {
  dict();
  if (route.params.id === 'create') {
    formData.value.fDate = new Date().toISOString().split('T')[0];
    formData.value.causeOfRejection = '';
  } else {
    formData.value = props.info;
    showData();
  }
});

watch(
  () => props.info,
  newVal => {
    if (newVal && route.params.id != 'create') {
      formData.value = newVal;
      showData();
    }
  },
  { immediate: true } // 初始化时立即执行
);

// 额外赋值
const handleBillTypeChange = value => {
  const selectedOption = findOptionByDictKey(value);
  if (selectedOption) {
    formData.value.fBillTypeId = value;
    formData.value.fBillTypeDictId = selectedOption.id;
    formData.value.fParentBillTypeDictId = selectedOption.parentId;
  }
};

const handleSaleOrgChange = value => {
  formData.value.fSaleOrgDictId = value;
  formData.value.realFOrgId = value;
  const option = findOption(value);
  if (option) {
    formData.value.fSaleOrgId = option.orgCode;
  }
};

const handleFForeOrgChange = value => {
  formData.value.fSaleOrgDictId = value;
  formData.value.realFOrgId = value;
  const option = findOption(value);
  if (option) {
    formData.value.fSaleOrgId = option.orgCode;
  }
};

const findOption = dictKey => {
  for (const option of ORG_LIST_CACHE.value) {
    if (option.id === dictKey) {
      return option;
    }
  }
  return null;
};

const findOptionByDictKey = dictKey => {
  for (const group of groupedOptions.value) {
    for (const option of group.children) {
      if (option.dictKey === dictKey) {
        return option;
      }
    }
  }
  return null;
};

// 分组逻辑：通过 parentId 将数据分组
const groupedOptions = computed(() => {
  return DC_BILL_TYPE.value;
});

const showData = () => {
  for (const group of groupedOptions.value) {
    for (const option of group.children) {
      if (option.dictKey === formData.value.fBillTypeId) {
        formData.value.fParentBillTypeDictId = option.parentId;
      }
    }
  }

  // 销售员
  SalersOptions.value.push({
    fnumber: formData.value.fSalerId,
    fname: formData.value.fSalerName,
  });

  customerOptions.value.push({
    customerFNumber: formData.value.fCustId,
    customerFName: formData.value.fCustName,
  });

  customerOptions.value.push({
    customerFNumber: formData.value.fOraBase,
    customerFName: formData.value.fOraBaseName,
  });

  currenciesOptinons.value.push({
    currencyCode: formData.value.fSettleCurrId,
    currencyName: formData.value.fSettleCurrName,
  });

  tpmOptions.value.push({
    fnumber: formData.value.fTpm,
    fname: formData.value.fTpmName,
  });

  documentariesOptions.value.push({
    fnumber: formData.value.fOraText3,
    fname: formData.value.fOraText3Name,
  });

  CollectionTermsOptions.value.push({
    fcode: formData.value.fRecConditionId,
    fname: formData.value.fRecConditionName,
  });

  // 项目编号
  projectNumbersOptions.value.push({
    fnumber: formData.value.fBdkBase,
    fname: formData.value.fBdkBaseName,
  });
};

const handleCustomerChange = selectedCustomerId => {
  // 根据选中的 customerFNumber 获取完整的客户数据
  const selectedCustomer = customerOptions.value.find(
    item => item.customerFNumber === selectedCustomerId
  );
  formData.value.fSettleCurrId = selectedCustomer.currencyCode;
  formData.value.fSettleCurrName = selectedCustomer.currencyName;
  // 汇率 税率
  formData.value.dcErpOrderItemList.forEach(item => {
    item.fExchangeRate = selectedCustomer.exchangeRate;
    item.fOraTaxRate = selectedCustomer.taxRateName;
  });
};

// 销售员
const handleFSalerChange = selectedCustomerId => {
  const selectedCustomer = SalersOptions.value.find(item => item.fnumber === selectedCustomerId);
  formData.value.fSaleDeptId = selectedCustomer.fdeptId;
  formData.value.fSaleDeptName = selectedCustomer.fdeptName;
};

// 保存数据
const submit = async () => {
  // proxy.$refs['ruleFormRef'].validate(async valid => {
  //   if (valid) {
  if (
    Array.isArray(formData.value.dcErpOrderItemList) &&
    formData.value.dcErpOrderItemList.length === 0
  ) {
    return proxy.$message({
      type: 'error',
      message: '请至少填写一项销售明细',
    });
  }
  loading.value = true;
  try {
    const res = await Api.pdp.dcErporder.submit(formData.value);
    const { code, msg } = res.data;
    if (code == 200) {
      proxy.$message.success(msg);
      router.push('/pdp/execution/list');
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
  //   }
  // });
};

// 提交
const passSubmit = async () => {
  if (
    !Array.isArray(formData.value.dcErpOrderItemList) || // 确保它是数组
    formData.value.dcErpOrderItemList.length === 0 || // 数组为空
    (formData.value.dcErpOrderItemList[0] &&
      formData.value.dcErpOrderItemList[0].fMaterialId == null) // 需要先判断 [0] 是否存在
  ) {
    proxy.$message({
      type: 'error',
      message: '请至少填写一项销售明细并且编码不能为空',
    });
  } else {
    dialogVisible.value = true;
    const res = await Api.pdp.erpSelect.headerAudit({ roleId: '1877174804015386626' });
    const { code, data } = res.data;
    if (code === 200) {
      roleIdOptions.value = data;
    }
  }
};

const confirmReject = id => {
  const form = {
    ...formData.value,
    tpmHeaderOperatorId: id,
  };

  proxy.$refs['ruleFormRef'].validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const res = await Api.pdp.dcErporder.pass(form);
        const { code, msg } = res.data;
        if (code == 200) {
          proxy.$message.success(msg);
          router.push('/pdp/execution/list');
        }
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
  });
};

// 获取字典
const dict = async () => {
  loading.value = true;
  try {
    const res = await Api.pdp.dcErporder.dict();
    const { code, data } = res.data;
    if (code == 200) {
      fEwDeviceAttributeType.value = data.设备属性;
      projectType.value = data.项目类型;
      fHeadDeliveryWayType.value = data.交货方式;
      unitType.value = data.计量单位;
      fEwFreeReasonType.value = data.免费原因;
      reservationType.value = data.预留类型;
      costType.value = data.成本类型;
      stageType.value = data.阶段;
      productSeriationType.value = data.客户产品;
      fEwProjectTypeOptions.value = data.项目类型;
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

const getDetail = async id => {
  try {
    loading.value = true;
    const res = await Api.pdp.dcErporder.detail({ id: id || route.params.id });
    const { code, msg, data } = res.data;
    if (code === 200) {
      formData.value = data;
      // 汇率 税率
      formData.value.dcErpOrderItemList.forEach(item => {
        item.fExchangeRate = formData.value.erpCustomer.exchangeRate;
        item.fOraTaxRate = formData.value.erpCustomer.taxRateName;
      });
      showData();
    } else {
      proxy.$message({
        type: 'warning',
        message: msg,
      });
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
  }
};

// 确认项目名称
const openProjectList = () => {
  ProjectListRef.value.openDialog();
};
/**
 * 结构就是机构
 * 电气电子都属于电控
 * */

// 确认项目名称
const confirmProjectList = data => {
  // 项目名称
  formData.value.projectId = data[0].projectId;
  // 销售组织
  formData.value.fSaleOrgDictId = data[0].fSaleOrgDictId;
  formData.value.fSaleOrgId = data[0].fSaleOrgId;
  // 预测组织
  formData.value.fForeOrgDictId = data[0].fSaleOrgDictId;
  formData.value.fForeOrgId = data[0].fSaleOrgId;
  // 销售员
  formData.value.fSalerId = data[0].fSalerId;
  formData.value.fSalerName = data[0].fSalerName;
  // 销售部门
  formData.value.fSaleDeptId = data[0].fSaleDeptId;
  formData.value.fSaleDeptName = data[0].fSaleDeptName;
  // 客户
  formData.value.fCustId = data[0].fCustId;
  formData.value.fCustName = data[0].fCustName;
  // 终端客户
  formData.value.fOraBase = data[0].fOraBase;
  formData.value.fOraBaseName = data[0].fOraBaseName;
  // TPM
  formData.value.fTpm = data[0].fTpm;
  formData.value.fTpmName = data[0].fTpmName;
  // 运营跟单
  formData.value.fOraText3 = data[0].fOraText3;
  formData.value.fOraText3Name = data[0].fOraText3Name;
  // 组织
  formData.value.realFOrgId = data[0].realFOrgId;
  formData.value.fBdkText7 = data[0].fBdkText7;
  formData.value.fBdkText7Name = data[0].fBdkText7Name;
  // 订单类型
  formData.value.fOraCombo = data[0].fOraCombo;
  formData.value.fOraComboDictId = data[0].fOraComboDictId;
  // 项目编号
  formData.value.fBdkBase = data[0].fBdkBase;
  formData.value.fBdkBaseName = data[0].fBdkBaseName;
  showData();
};

// 远程搜索获取客户列表
const remoteCustomerOptions = async name => {
  if (name && name.length <= 2) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      name,
    };
    const res = await Api.pdp.erpSelect.customers(params);
    const { code, data } = res.data;
    if (code === 200) {
      customerOptions.value = data;
    }
  }
};

// 远程搜索获取物料编码列表
const remoteMaterialsOptions = async name => {
  if (name && name.length >= 2) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      name: name,
    };
    const res = await Api.pdp.erpSelect.materials(params);
    const { code, data } = res.data;
    if (code === 200) {
      materialsOptinons.value = data;
    }
  }
};

// 远程搜索获取物料编码列表
const remoteFMaterialOptions = async number => {
  if (number && number.length >= 5) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      number: number,
    };
    const res = await Api.pdp.erpSelect.materials(params);
    const { code, data } = res.data;
    if (code === 200) {
      materialsOptinons.value = data;
    }
  }
};

// 远程搜索获取物料tpm列表
const remoteTpmOptions = async name => {
  if (name) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      name,
    };
    const res = await Api.pdp.erpSelect.tpm(params);
    const { code, data } = res.data;
    if (code === 200) {
      tpmOptions.value = data;
    }
  }
};

// 远程搜索获取销售员列表
const remoteSalersOptions = async name => {
  if (name) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      name,
    };

    const res = await Api.pdp.erpSelect.salers(params);
    const { code, data } = res.data;
    if (code === 200) {
      SalersOptions.value = data;
    }
  }
};

// 远程搜索运营跟单
const remoteDocumentariesOptions = async name => {
  if (name) {
    const params = {
      orgId: formData.value.fSaleOrgDictId,
      name,
    };
    const res = await Api.pdp.erpSelect.documentaries(params);
    const { code, data } = res.data;
    if (code === 200) {
      documentariesOptions.value = data;
    }
  }
};

const handleMaterialChange = row => {
  // 根据选中的编码找到对应的物料名称
  const selectedMaterial = materialsOptinons.value.find(item => item.fname === row.fMaterialName);
  if (selectedMaterial) {
    fparentId.value = selectedMaterial.fparentId;
    row.fMaterialId = selectedMaterial.fnumber;
    row.fMaterialName = selectedMaterial.fname;
    row.fMaterialModel = selectedMaterial.fspecification; //更新规格型号
    row.fUnitId = selectedMaterial.funitId;
    row.fUnitName = selectedMaterial.funitName; // //更新单位
  } else {
    row.fMaterialId = ''; // 如果未找到，清空物料编码
    row.fMaterialName = '';
    row.fMaterialModel = ''; // 如果未找到，清空规格型号
    row.fUnitId = '';
    row.fUnitName = ''; //如果未找到，清空单位
  }
};

const handleFMaterialChange = row => {
  // 根据选中的编码找到对应的物料名称
  const selectedMaterial = materialsOptinons.value.find(item => item.fnumber === row.fMaterialId);
  if (selectedMaterial) {
    fparentId.value = selectedMaterial.fparentId;
    row.fMaterialId = selectedMaterial.fnumber;
    row.fMaterialName = selectedMaterial.fname;
    row.fMaterialModel = selectedMaterial.fspecification; //更新规格型号
    row.fUnitId = selectedMaterial.funitId;
    row.fUnitName = selectedMaterial.funitName; // //更新单位
  } else {
    row.fMaterialId = ''; // 如果未找到，清空物料编码
    row.fMaterialName = '';
    row.fMaterialModel = ''; // 如果未找到，清空规格型号
    row.fUnitId = '';
    row.fUnitName = ''; //如果未找到，清空单位
  }
};

// 远程搜索获取项目编号列表
const remoteProjectNumbersOptions = async fullname => {
  const form = {
    orgId: formData.value.fSaleOrgDictId,
    name: fullname,
    number: fullname,
  };
  const res = await Api.pdp.erpSelect.projectNumbers(form);
  const { code, data } = res.data;
  if (code === 200) {
    projectNumbersOptions.value = data;
  }
};

const handleCopy = () => {
  if (!selectedRow.value) {
    proxy.$message.warning('请先选中一行数据进行复制');
    return;
  }
  const row = { ...selectedRow.value, isNew: true };
  const copiedRow = JSON.parse(JSON.stringify(row)); // 深拷贝
  delete copiedRow.id;
  formData.value.dcErpOrderItemList.push(copiedRow);
  // 自动设置为编辑状态
  editRowIndex.value = formData.value.dcErpOrderItemList.length - 1;
  openConfig.value = true;
  originalRowData.value = JSON.parse(JSON.stringify(copiedRow)); // 保存原始数据

  singleSelectTable.value.clearSelection(); // 清空选中状态
  singleSelectTable.value.toggleRowSelection(copiedRow, true); // 设置当前行选中状态
  selectedRow.value = copiedRow; // 更新选中行
};

// 新增行
const handleAdd = async () => {
  if (formData.value.id === undefined || formData.value.id === null || formData.value.id === '') {
    loading.value = true;
    proxy.$refs['ruleFormRef'].validate(async valid => {
      if (valid) {
        try {
          const res = await Api.pdp.dcErporder.submit(formData.value);
          const { code, data, msg } = res.data;
          if (code == 200) {
            proxy.$message.success(msg);
            formData.value = data;
            formData.value.dcErpOrderItemList = [];
            await getDetail(data.id);
            doAddTableLine();
          }
        } catch (error) {
          loading.value = false;
        }
      }
    });
  } else {
    doAddTableLine();
  }
};

const doAddTableLine = () => {
  let newRow;
  // 空对象表示一个值
  // 明细 预测单 销售部门是TPM带出来的
  if (formData.value.fParentBillTypeDictId == '1870708551385808898') {
    newRow = {
      isNew: true,
      //物料编码
      fMaterialId: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fMaterialId
        : null,
      // 明细TPM
      fEwTpm: formData.value.fTpm,
      // 明细库存组织
      fStockOrgDictId: formData.value.fSaleOrgDictId,
      fStockOrgId: formData.value.fSaleOrgId,
      fStockOrgDictName: formData.value.fSaleOrgDictName,
      // 明细供应组织
      fSupplyOrgDictId: formData.value.fForeOrgDictId,
      fSupplyOrgId: formData.value.fForeOrgId,
      fSupplyOrgDictName: formData.value.fForeOrgDictName,
      // 货主
      fOwnerDictId: formData.value.fSaleOrgDictId,
      fOwnerId: formData.value.fSaleOrgId,
      fOwnerDictName: formData.value.fSaleOrgDictName,
      // 客户
      fCustId: formData.value.fCustId,
      fCustIdName: formData.value.fCustName,
      // 终端客户
      fOraBase4: formData.value.fOraBase,
      fOraBase4Name: formData.value.fOraBaseName,
      // 项目
      fEwProjectType: formData.value.fBdkText7,
      fEwProjectTypeName: formData.value.fBdkText7Name,
      // 订单类型
      fOraCombo: formData.value.fOraCombo,
      // 汇率 税率
      fExchangeRate: formData.value.erpCustomer.exchangeRate,
      fOraTaxRate: formData.value.erpCustomer.taxRateName,
      // 结算币别
      fSettleCurrId: formData.value.fSettleCurrId,
      fSettleCurrIdName: formData.value.fSettleCurrName,
      // 销售员
      fBdkBase1: formData.value.fSalerId,
      fBdkBase1Name: formData.value.fSalerName,
      // 销售部门
      fEwSaleDeptId: formData.value.ftpmDeptId,
      fEwSaleDeptIdName: formData.value.ftpmDeptName,
      // 设备属性
      fEwDeviceAttribute: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwDeviceAttribute
        : null,
      fEwDeviceAttributeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwDeviceAttributeName
        : null,
      // 项目类型
      fEwProjectType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProjectType
        : null,
      fEwProjectTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProjectTypeName
        : null,
      // 客户产品
      fEwCustomerProduct: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCustomerProduct
        : null,
      fEwCustomerProductName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCustomerProductName
        : null,
      // 免费原因
      fEwFreeReason: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwFreeReason
        : null,
      fEwFreeReasonName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwFreeReasonName
        : null,
      // 成本类型
      fEwCostType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCostType
        : null,
      fEwCostTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCostTypeName
        : null,
      // 成本归属专案
      fCostAttrMtoNo: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fCostAttrMtoNo
        : null,
      fCostAttrMtoNoName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fCostAttrMtoNoName
        : null,
      // 项目名称
      fOraAssistant1: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fOraAssistant1
        : null,
      fOraAssistant1Name: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fOraAssistant1Name
        : null,
      // 阶段
      fEwPhase: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwPhase
        : null,
      fEwPhaseName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwPhaseName
        : null,
      // 产品系列
      fEwProducSeriesId: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProducSeriesId
        : null,
      fEwProducSeriesName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProducSeriesName
        : null,
      // 软件工程
      fBdkText12: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText12
        : null,
      // 电子工程
      fBdkText11: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText11
        : null,
      // 电气工程
      fBdkText10: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText10
        : null,
      // 机构工程
      fBdkText9: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText9
        : null,
      // 内部PM
      fBdkText8: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText8
        : null,
      // 结算币种
      fSettleCurrId: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fSettleCurrId
        : null,
      fSettleCurrName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fSettleCurrName
        : null,
      // 均化类型
      fAveraType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fAveraType
        : null,
      fAveraTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fAveraTypeName
        : null,
      // 预留类型
      fReserveType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fReserveType
        : null,
      fReserveTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fReserveTypeName
        : null,
    };
  } else {
    newRow = {
      isNew: true,
      //物料编码
      fMaterialId: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fMaterialId
        : null,
      // 明细TPM
      fEwTpm: formData.value.fTpm,
      // 明细库存组织
      fStockOrgDictId: formData.value.fSaleOrgDictId,
      fStockOrgId: formData.value.fSaleOrgId,
      fStockOrgDictName: formData.value.fSaleOrgDictName,
      // 明细结算组织
      fPeSettleOrgDictId: formData.value.fSaleOrgDictId,
      fPeSettleOrgId: formData.value.fSaleOrgId,
      fPeSettleOrgDictName: formData.value.fSaleOrgDictName,
      // 货主
      fOwnerDictId: formData.value.fSaleOrgDictId,
      fOwnerId: formData.value.fSaleOrgId,
      fOwnerDictName: formData.value.fSaleOrgDictName,
      // 明细供应组织
      fSupplyOrgDictId: formData.value.fSaleOrgDictId,
      fSupplyOrgId: formData.value.fSaleOrgId,
      fSupplyOrgDictName: formData.value.fSaleOrgDictName,
      // 客户
      fCustId: formData.value.fCustId,
      fCustName: formData.value.fCustName,
      // 终端客户
      fOraBase4: formData.value.fOraBase,
      fOraBase4Name: formData.value.fOraBaseName,
      // 项目
      fEwProjectType: formData.value.fBdkText7,
      fEwProjectTypeName: formData.value.fBdkText7Name,
      // 设备属性
      fEwDeviceAttribute: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwDeviceAttribute
        : null,
      fEwDeviceAttributeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwDeviceAttributeName
        : null,
      // 项目类型
      fEwProjectType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProjectType
        : null,
      fEwProjectTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProjectTypeName
        : null,
      // 客户产品
      fEwCustomerProduct: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCustomerProduct
        : null,
      fEwCustomerProductName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCustomerProductName
        : null,
      // 免费原因
      fEwFreeReason: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwFreeReason
        : null,
      fEwFreeReasonName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwFreeReasonName
        : null,
      // 成本类型
      fEwCostType: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCostType
        : null,
      fEwCostTypeName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwCostTypeName
        : null,
      // 成本归属专案
      fCostAttrMtoNo: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fCostAttrMtoNo
        : null,
      fCostAttrMtoNoName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fCostAttrMtoNoName
        : null,
      // 项目名称
      fOraAssistant1: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fOraAssistant1
        : null,
      fOraAssistant1Name: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fOraAssistant1Name
        : null,
      // 阶段
      fEwPhase: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwPhase
        : null,
      fEwPhaseName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwPhaseName
        : null,
      // 产品系列
      fEwProducSeriesId: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProducSeriesId
        : null,
      fEwProducSeriesName: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fEwProducSeriesName
        : null,
      // 软件工程
      fBdkText12: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText12
        : null,
      // 电子工程
      fBdkText11: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText11
        : null,
      // 电气工程
      fBdkText10: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText10
        : null,
      // 机构工程
      fBdkText9: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText9
        : null,
      // 内部PM
      fBdkText8: formData.value.dcErpOrderConfigure
        ? formData.value.dcErpOrderConfigure.fBdkText8
        : null,
    };
  }

  // 遍历并检查 isNew 属性
  for (let item of formData.value.dcErpOrderItemList) {
    if (item.isNew === true) {
      proxy.$message.success('请检查是否填写完成');
      return; // 直接结束函数
    }
  }

  passDisabled.value = false;
  formData.value.dcErpOrderItemList.push(newRow);
  numberIndex.value = formData.value.dcErpOrderItemList.length - 1;

  // 自动设置为编辑状态
  editRowIndex.value = formData.value.dcErpOrderItemList.length - 1;
  openConfig.value = true;
  originalRowData.value = JSON.parse(JSON.stringify(newRow)); // 保存原始数据
};

/** 删除按钮操作 */
const handleDelete = () => {
  if (!selectedRow.value?.id) {
    proxy.$message.warning('请先选中一行，进行删除！');
    return;
  }
  const configIds = { ids: selectedRow.value.id };
  proxy
    .$confirm('是否确认删除参数编号为"' + configIds.ids + '"的数据项？')
    .then(async () => {
      return await Api.pdp.erpSelect.delete(configIds);
    })
    .then(() => {
      proxy.$message.success('删除成功');
      getDetail(formData.value.id);
    })
    .catch(() => {});
};

const getVersionRules = () => {
  return fparentId.value === '337718'
    ? [] // 不进行校验
    : [{ required: true, message: '请选择版本号', trigger: 'change' }];
};

// 双击打开编辑行
const handleRowDbclick = row => {
  openConfig.value = true;
  passDisabled.value = false;
  // 获取点击行的索引
  const rowIndex = formData.value.dcErpOrderItemList.indexOf(row);
  editRowIndex.value = rowIndex;
  originalRowData.value = JSON.parse(JSON.stringify(row)); // 保存原始数据
};

const handleRowClick = row => {
  // 获取当前行的下标
  const rowIndex = formData.value.dcErpOrderItemList.findIndex(item => item === row);
  numberIndex.value = rowIndex;
  // 清空之前的选中状态
  if (singleSelectTable.value) {
    singleSelectTable.value.clearSelection();
  }
  // 设置当前行为选中状态
  if (singleSelectTable.value) {
    singleSelectTable.value.toggleRowSelection(row);
  }
};

// 确认编辑
const configSubmit = (row, rowIndex) => {
  proxy.$refs['ruleTableRef'].validate(async (valid, fields) => {
    if (valid) {
      delete row.isNew;
      const form = {
        ...row,
        dcErpOrderId: formData.value.id,
      };
      const res = await Api.pdp.dcErporder.orderSubmit(form);
      const { code, msg } = res.data;
      if (code === 200) {
        passDisabled.value = true;
        getDetail(formData.value.id);
        proxy.$message(msg);
        editRowIndex.value = false;
        originalRowData.value = null; // 清空保存的原始数据
      }
    } else {
      const field = Object.keys(fields)[0];
      const target = `${field}-${rowIndex}`;
      window.location.hash = '';
      window.location.hash = `${target}`;
    }
  });
};

// 取消编辑
const Cancel = (row, rowIndex) => {
  if (row.isNew) {
    // 如果是新增行，直接删除
    formData.value.dcErpOrderItemList.splice(rowIndex, 1);
  } else if (originalRowData.value) {
    // 恢复原始数据
    formData.value.dcErpOrderItemList[rowIndex] = JSON.parse(JSON.stringify(originalRowData.value));
  }
  passDisabled.value = true;
  editRowIndex.value = null; // 退出编辑状态
  originalRowData.value = null; // 清空原始数据
  selectedRow.value = null; // 清空选中行，防止复制操作错误
};

// 选中变化事件
const handleSelectionChange = selection => {
  // 保证只有一行被选中，取消多选
  if (selection.length > 1) {
    // 如果多选，清空选中项并只选中最后一行
    singleSelectTable.value.clearSelection();
    const lastSelected = selection[selection.length - 1];
    singleSelectTable.value.toggleRowSelection(lastSelected, true);
    selectedRow.value = lastSelected; // 更新选中行
  } else {
    selectedRow.value = selection[0] || null; // 更新选中行
  }
};
</script>
<style lang="scss">
.audit {
  .el-dialog__body {
    height: auto !important;
  }
}
</style>
<style scoped lang="scss">
:deep(.el-form-item__content) {
  display: flex;
  justify-content: space-around;
}
.audit {
  .el-dialog__body {
    height: auto !important;
  }
}
.wrap-left-form {
  display: flex;
  justify-content: center;
}

.form-center {
  display: flex;
  flex-wrap: wrap;
}

.form-group-header-title {
  margin: 28px 0 20px 0 !important;
}

.form-group-header-btn {
  margin-bottom: 22px;
}

.form-group-title {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 28px 0 32px 0;
  font-weight: 600;
  font-size: 16px;
  color: #333;

  &::before {
    margin-right: 4px;
    display: block;
    content: '';
    width: 4px;
    height: 13px;
    background-color: #f78431;
  }

  .add-box {
    display: flex;
    align-items: center;
    margin-left: 40px;
    font-weight: 400;
    font-size: 14px;
    color: #f78431;
    cursor: pointer;
  }
}

.form-item-row {
  width: 93% !important;
}

.form-item-width {
  width: 100%;
}

.ipt {
  width: 100%;
  border: 0px;
  background: none;
}
.form-display {
  display: flex;
  justify-content: space-around;
  :deep(.el-form-item__label) {
    font-size: 16px;
  }
  :deep(.el-form-item__content) {
    font-size: 16px;
  }
}
</style>
